package com.powernode.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.config.WxTokenProperties;
import com.powernode.constant.AuthConstant;
import com.powernode.domain.LoginUser;
import com.powernode.domain.SysLoginUser;
import com.powernode.mapper.LoginUserMapper;
import com.powernode.mapper.SysLoginUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 内容:
 * 作者: cy
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysLoginUserMapper sysLoginUserMapper;

    @Autowired
    private WxTokenProperties wxTokenProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoginUserMapper loginUserMapper;


    /**
     * 这里就自定义查询数据库等操作
     * 区分前台用户和后台的用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if (StringUtils.isEmpty(loginType)) {
            log.error("平台类型为空，非法请求,ip为{}", request.getRemoteHost());
            return null;
        }
        // jdk1.7
        switch (loginType) {
            case AuthConstant.SYS_USER:
                // 查询后台的表
                SysLoginUser sysLoginUser = sysLoginUserMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>()
                        .eq(SysLoginUser::getUsername, username)
                );
                if (!ObjectUtils.isEmpty(sysLoginUser)) {
                    // 查询权限
                    List<String> auths = sysLoginUserMapper.selectAuthsById(sysLoginUser.getUserId());
                    sysLoginUser.setAuths(auths);
                }
                return sysLoginUser;
            case AuthConstant.MEMBER:
                // 查询前台的表  此时 username 就是code
                // appid  appsecret code  url
                String tokenUrl = wxTokenProperties.getTokenUrl();
                String realTokenUrl = String.format(tokenUrl, wxTokenProperties.getAppId(), wxTokenProperties.getAppSecret(), username);
                // 发一个请求
                String wxTokenStr = restTemplate.getForObject(realTokenUrl, String.class);
                JSONObject jsonObject = JSON.parseObject(wxTokenStr);
                String openid = jsonObject.getString("openid");
                if (!StringUtils.hasText(openid)) {
                    // 有问题
                    log.error("获取openId失败，原因为{}", jsonObject.toJSONString());
                    return null;
                }
                // 如果这个openId拿到了  就去查询数据库
                // 如果数据库存在  那么就查出来 返回user对象即可
                // 如果不存在 那么就帮他注册一个 因为微信小程序是默认登录和注册的
                LoginUser loginUser = loginUserMapper.selectOne(new LambdaQueryWrapper<LoginUser>()
                        .eq(LoginUser::getUserId, openid)
                );
                if (ObjectUtils.isEmpty(loginUser)) {
                    // 那么就帮他注册一个 因为微信小程序是默认登录和注册的
                    loginUser = createUser(openid, request);
                }
                return loginUser;
            default:
                return null;
        }
    }

    /**
     * 注册用户的方法
     *
     * @param openid
     * @param request
     * @return
     */
    private LoginUser createUser(String openid, HttpServletRequest request) {
        LoginUser loginUser = new LoginUser();
        String ip = request.getRemoteAddr();
        loginUser.setUserId(openid);
        loginUser.setStatus(1);
        loginUser.setUserRegtime(new Date());
        loginUser.setModifyTime(new Date());
        loginUser.setUserLasttime(new Date());
        loginUser.setUserRegip(ip);
        loginUser.setUserLastip(ip);
        loginUserMapper.insert(loginUser);
        return loginUser;
    }
}
